<?php
class UserComponent extends CApplicationComponent
{   	
	/**
	 * @var int
	 * @desc items on page
	 */
	public $user_page_size = 10;
	
	/**
	 * @var int
	 * @desc items on page
	 */
	public $fields_page_size = 10;
	
	/**
	 * @var string
	 * @desc hash method (md5,sha1 or algo hash function http://www.php.net/manual/en/function.hash.php)
	 */
	public $hash = 'md5';
	
	/**
	 * @var boolean
	 * @desc use email for activation user account
	 */
	public $sendActivationMail = true;
	
	/**
	 * @var boolean
	 * @desc allow auth for is not active user
	 */
	public $loginNotActiv = false;
	
	/**
	 * @var boolean
	 * @desc activate user on registration (only $sendActivationMail = false)
	 */
	public $activeAfterRegister = false;
	
	/**
	 * @var boolean
	 * @desc login after registration (need loginNotActiv or activeAfterRegister = true)
	 */
	public $autoLogin = false;
    
	// configuration related control vars

	public $enableLogging = true;
	public $enableOnlineStatus = true;	
    
	public $fieldsMessage = '';
	
	/**
	 * @var array
	 * @desc User model relation from other models
	 * @see http://www.yiiframework.com/doc/guide/database.arr
	 */
	public $relations = array();
	
	/**
	 * @var array
	 * @desc Profile model relation from other models
	 */
	public $profileRelations = array();
	
	/**
	 * @var boolean
	 */
	public $captcha = array('registration'=>true);
    
    public $loginUrl = array("/user/login");
	public $logoutUrl = array("/user/logout");
	public $registrationUrl = array("/user/registration");
	public $recoveryUrl = array("/user/recovery/recovery");
	public $profileUrl = array("/user/profile");
	public $returnUrl = array();
    
    /**
     * path, default width for avatar images
     */
    public $imagePath = '/images';    
    public $avatarUploadPath = '/avatar/upload';
    public $avatarDefaultPath = '/avatar/default';
    
    public $avatarMale = '/avatar/default/default_avatar_male.png';
    public $avatarFemale = '/avatar/default/default_avatar_female.png';
    
    public $avatarThumbnailWidth = 45; // For display in user browse, friend list
	public $avatarDisplayWidth = 200;
    
	/**
	 * @var boolean
	 */
	//public $cacheEnable = false;	
	
	static private $_user;
	static private $_admin;
	static private $_admins;
	
	/**
	 * @var array
	 * @desc Behaviors for models
	 */
	public $componentBehaviors=array();
    
    public function getBehaviorsFor($componentName){
        if (isset($this->componentBehaviors[$componentName])) {
            return $this->componentBehaviors[$componentName];
        } else {
            return array();
        }
	}
    
    /**
	 * @return hash string.
	 */
	public function encrypting($string="") {
		$hash = Yii::app()->usercomponent->hash;
		if ($hash=="md5")
			return md5($string);
		if ($hash=="sha1")
			return sha1($string);
		else
			return hash($hash,$string);
	}
    
    /**
	 * @param $place
	 * @return boolean 
	 */
	public function doCaptcha($place = '') {
		if(!extension_loaded('gd'))
			return false;
		if (in_array($place, Yii::app()->usercomponent->captcha))
			return Yii::app()->usercomponent->captcha[$place];
		return false;
	}
    
    /**
	 * Send mail method
	 * @param string $email Receiver email
	 * @param string $subject Subject of the email
	 * @param string $message
	 * @param string $view View name (message=null)
	 * @param array $vars Variables (use to getView)
	 */
    public function sendMail($email,$subject,$message=null,$view=null,$vars=array()) {
    	//$adminEmail = Yii::app()->params['adminEmail'];
//	    $headers = "MIME-Version: 1.0\r\nFrom: $adminEmail\r\nReply-To: $adminEmail\r\nContent-Type: text/html; charset=utf-8";
//	    $message = wordwrap($message, 70);
//	    $message = str_replace("\n.", "\n..", $message);
//	    return mail($email,'=?UTF-8?B?'.base64_encode($subject).'?=',$message,$headers);
        global $error;
        $mailer = Yii::app()->mailer;
        $mailer->Host = 'smtp.gmail.com';
        $mailer->IsSMTP();
        $mailer->From = 'support@letgo24.com';
        $mailer->AddReplyTo('quyet.le@letgo24.com');
        $mailer->AddAddress($email);
        $mailer->FromName = 'Maximath';
        $mailer->CharSet = 'UTF-8';
        $mailer->Username='support@letgo24.com';
        $mailer->Password='s4pp0rt123';
        $mailer->Port = '465';
        $mailer->SMTPAuth=true;
        $mailer->SMTPSecure = 'ssl';
        $mailer->Subject = $subject;
        /*
        if($view)
        	$mailer->getView($view,$vars,'default');
       	else $mailer->getView('default',array('vars'=>$vars),'default');
        */
       	//else $mailer->getLayout('default',array('message'=>$message));
        $mailer->Body = $message;
        $mailer->isHTML(true);
        if(!$mailer->Send()) {
            $error = 'Mail error: '.$mailer->ErrorInfo;
            throw new CException(Yii::t('EMailer',$error));
            return false;
        } else {
            $error = 'Message sent!';
            Yii::log($error);
            return true;
        }
    }
    
    /**
     * Return assigned role of user
     */
    public function getUserRole($userId=null)
    {
        if($userId==null)
            $userId = Yii::app()->user->id;
        $arrayAuthItems = Rights::getAssignedRoles($userId);
        $arrayKeys = array_keys($arrayAuthItems);
        if(isset($arrayKeys)){
            $authItem = $arrayKeys[0];
            return $authItem;
            //$this->forward('profile',true);
        }
    }
    
    public function getDefaultUrl()
    {
        $returnUrl = null;
        
        switch($this->getUserRole()) {
            case "Teacher":
                $returnUrl = array("/master/index");
                break;
            case "Parent":
                $returnUrl = array("/master/index");
                break;
            case "Student":
                $returnUrl = array("/student/");
                break;
            default:
                $returnUrl = Yii::app()->homeUrl;
                break;
        }
        return $returnUrl;
	}
}
?>